import logging

from flask import Blueprint
from flask import jsonify
from flask import request
from sqlalchemy.exc import IntegrityError

from airflow.patsnap.service import folder_service
from airflow.models.idata_folder import Folder
from airflow.www.api import exception_handle

log = logging.getLogger(__name__)

folder_bp = Blueprint('folder_bp', __name__)


@folder_bp.route('/folders/<int:folder_id>', methods=['GET'])
@exception_handle
def get_folder(folder_id):
    folder = Folder.get_folder(folder_id)
    if folder:
        return jsonify(code=0, message='ok', data=folder.to_json())
    else:
        return jsonify(code=404, message='folder not found', data=None)


@folder_bp.route('/folders/tree', methods=['GET'])
@exception_handle
def get_project_tree():
    project_id = request.args.get('project_id', None)
    if project_id:
        result = folder_service.get_tree(project_id)
        return jsonify(code=0, message='ok', data=result)
    else:
        return jsonify(code=400, message='param project_id is null', data=None)


@folder_bp.route('/folders', methods=['GET'])
@exception_handle
def query_folder():
    project_id = request.args.get('project_id', None)
    category = request.args.get('category', None)
    level = request.args.get('level', None)

    if project_id:
        rs = [folder.to_json() for folder in Folder.query(project_id, category, level)]
        return jsonify(code=0, message='ok', data=rs)
    else:
        return jsonify(code=400, message='project_id is null', data=None)


@folder_bp.route('/folders', methods=['POST'])
@exception_handle
def insert():
    data = request.get_json()
    folder = Folder(**data)
    try:
        folder.insert()
    except IntegrityError as err:
        return jsonify(code=500, message=str(err), data=None)
    return jsonify(code=0, message='ok', data=folder.to_json())


@folder_bp.route('/folders/<int:folder_id>', methods=['PUT'])
@exception_handle
def update(folder_id):
    data = request.get_json()
    if 'id' not in data:
        data['id'] = folder_id
    folder = Folder(**data)
    folder.update()
    return jsonify(code=0, message='ok', data=folder.to_json())


@folder_bp.route('/folders/<int:folder_id>', methods=['DELETE'])
@exception_handle
def delete(folder_id):
    folder_service.delete(folder_id)
    return jsonify(code=0, message='ok', data=None)
